package mushystuff.dtb.web.controller.admin;

import javax.servlet.http.HttpSession;

import mushystuff.dtb.core.model.Product;
import mushystuff.dtb.web.controller.BaseController;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class ProductsAdmin extends BaseController {

    @ModelAttribute("newProduct")
    public Product newProduct() {
        return new Product();
    }

    @RequestMapping(value = "/productsAdmin.do", method = RequestMethod.GET)
    public String viewProducts(HttpSession session, ModelMap model) {
        model.addAttribute("productList", productService.getAllProducts());
        session.removeAttribute("productId");
        return "dtb.admin.products";
    }

    @RequestMapping(value = "/productsAdmin.do", method = RequestMethod.POST)
    public String submitForm(@ModelAttribute("newProduct") Product newProduct,
            HttpSession session, ModelMap model) {
        productService.createUpdateProduct(newProduct);
        model.addAttribute("productSelectorList", productService
                .getAllActiveProducts());
        return viewProducts(session, model);
    }

    @RequestMapping("/activateProduct.do")
    public String activateProduct(
            @RequestParam(value = "productId", required = true) Long productId) {
        Product product = productService.getProduct(productId);
        product.setActive(true);
        productService.createUpdateProduct(product);
        return "redirect:productsAdmin.do";
    }

    @RequestMapping("/deactivateProduct.do")
    public String deactivateProduct(
            @RequestParam(value = "productId", required = true) Long productId) {
        Product product = productService.getProduct(productId);
        product.setActive(false);
        productService.createUpdateProduct(product);
        return "redirect:productsAdmin.do";
    }
}
